<template>
    <el-dialog :title="dialogStatus | titleFilter" :close-on-click-modal="false" width="600px" :visible.sync="visible">
        <el-form ref="temp" :model="temp" :rules="rule" label-width="80px" @keyup.enter.native="dataFormSubmit()">

            <el-form-item label="用户名" prop="userName">
                <el-input v-model="temp.userName" placeholder="用户名" />
            </el-form-item>

            <el-form-item label="密码" prop="password">
                <el-input v-model="temp.password" placeholder="密码" />
            </el-form-item>

            <el-form-item label="确认密码" prop="comfirmPassword">
                <el-input v-model="temp.comfirmPassword" placeholder="确认密码" />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
                <el-input v-model="temp.email" placeholder="邮箱" />
            </el-form-item>

            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="temp.mobile" placeholder="手机号" />
            </el-form-item>

            <el-form-item label="角色" prop="roleIdList">
                <el-checkbox-group v-model="temp.roleIdList">
                    <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleName }}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>

            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="temp.status">
                    <el-radio :label="0">禁用</el-radio>
                    <el-radio :label="1">正常</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="所属部门" prop="deptName">
                <el-popover ref="menuListPopover" v-model="buMenVisible" placement="bottom-start" trigger="click">
                    <el-tree ref="menuListTree" :data="branchList" :props="menuListTreeProps" node-key="deptId" :default-expand-all="true"
                        :highlight-current="true" :expand-on-click-node="false" @current-change="menuListTreeCurrentChangeHandle" />
                </el-popover>
                <el-input v-model="temp.deptName" v-popover:menuListPopover :readonly="true" placeholder="分支名称" class="menu-list__input" />
            </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="visible = false">
                取消
            </el-button>
            <el-button type="primary" @click="dataFormSubmit">
                确认
            </el-button>
        </span>
    </el-dialog>
</template>
<script>
import { treeDataTranslate } from '@/utils'
import { validEmail, isMobile } from '@/utils/validate'
import { getOtherUserInfo, selectRoleList, createUserList, updateUserList, selectSysDept } from '@/api/permission'
export default {
    filters: {
        // 过滤弹框的标题
        titleFilter (type) {
            const textMap = {
                create: '新增',
                update: '修改'
            }
            return textMap[type]
        }
    },
    data () {
        var validatePassword = (rule, value, callback) => {
            if (!this.temp.id && !/\S/.test(value)) {
                callback(new Error('密码不能为空'))
            } else {
                callback()
            }
        }
        var validateComfirmPassword = (rule, value, callback) => {
            if (!this.temp.id && !/\S/.test(value)) {
                callback(new Error('确认密码不能为空'))
            } else if (this.temp.password !== value) {
                callback(new Error('确认密码与密码输入不一致'))
            } else {
                callback()
            }
        }
        var validateEmail = (rule, value, callback) => {
            if (!validEmail(value)) {
                callback(new Error('邮箱格式错误'))
            } else {
                callback()
            }
        }
        var validateMobile = (rule, value, callback) => {
            if (!isMobile(value)) {
                callback(new Error('手机号格式错误'))
            } else {
                callback()
            }
        }
        return {
            visible: false,
            roleRadio: 1, // 角色类型
            dialogStatus: '', // 弹框新增或者修改
            temp: { // 表单数据
                userId: 0,
                userName: '',
                password: '',
                comfirmPassword: '',
                salt: '',
                email: '',
                mobile: '',
                roleIdList: [],
                status: 1,
                deptId: '',
                deptName: ''
            },
            rule: {
                userName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
                password: [{ validator: validatePassword, trigger: 'blur' }],
                comfirmPassword: [{ validator: validateComfirmPassword, trigger: 'blur' }],
                email: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }, { validator: validateEmail, trigger: 'blur' }],
                mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }, { validator: validateMobile, trigger: 'blur' }],
                status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
                roleIdList: [{ required: true, message: '状态不能为空', trigger: 'change' }]
            },
            roleList: [], // 菜单树 数据
            branchList: [], // 部门树 数据
            buMenVisible: false, // 部门树显示隐藏
            menuListTreeProps: {
                label: 'name',
                children: 'children'
            }
        }
    },
    created () {
        this.getRoleList()
        this.getParentBranchList()
    },
    methods: {
        // 初始化
        init (status, param) {
            this.dialogStatus = status // 标题
            this.visible = true // 显示
            this[status](param) // 新增或者修改
            this.$nextTick(() => { // 重置表单
                this.$refs['temp'].clearValidate()
            })
        },
        create () {
            this.resetTemp() // 清空表单
        },
        async update (param) {
            // let data = Object.assign({}, param)  .//从上一页带过来当前的数据
            const { data, code } = await getOtherUserInfo(param.userId) // 从后台获取当前的的数据
            // 失败
            // if (code != 200) { this.$message.error('用户信息获取失败'); return };
            // 成功
            this.temp.userId = data.userId
            this.temp.userName = data.username
            this.temp.email = data.email
            this.temp.mobile = data.mobile
            this.temp.password = ''
            this.temp.comfirmPassword = ''
            this.temp.roleIdList = data.roleIdList
            this.temp.status = data.status
            this.temp.salt = data.salt
            this.temp.deptId = data.deptId
            this.$refs.menuListTree.setCurrentKey(data.deptId) // 设置 所属部门 树形 当前是哪一个
            this.temp.deptName = (this.$refs.menuListTree.getCurrentNode() || {})['name'] // 后太不会返回 deptName 要根据 deptId 去找
        },
        // 新增数据清空表单数据
        resetTemp () {
            this.temp = {
                userId: '',
                userName: '',
                password: '',
                comfirmPassword: '',
                salt: '',
                email: '',
                mobile: '',
                roleIdList: [],
                status: 1,
                deptId: '',
                deptName: ''
            }
        },
        // 获取所有角色
        async getRoleList () {
            const { data, code } = await selectRoleList()
            // if (code != 200) { this.$message.error(message); return }; //失败
            this.roleList = data
        },
        // 获取所有部门
        async getParentBranchList () {
            const { data, code } = await selectSysDept()
            // if (code != 200) { this.$message.error(message); return }; //失败
            this.branchList = treeDataTranslate(data, 'deptId')
        },
        // 上级菜单树选中
        menuListTreeCurrentChangeHandle (data) {
            this.temp.deptId = data.deptId
            this.temp.deptName = data.name
        },
        // 表单提交
        dataFormSubmit () {
            this.$refs['temp'].validate(async (valid) => {
                if (!valid) return
                const params = {
                    userId: this.temp.userId || undefined,
                    username: this.temp.userName,
                    password: this.temp.password,
                    email: this.temp.email,
                    mobile: this.temp.mobile,
                    status: this.temp.status,
                    roleIdList: this.temp.roleIdList,
                    deptName: this.temp.deptName,
                    deptId: this.temp.deptId,
                    // salt: this.temp.salt
                }
                const textMap = {
                    create: createUserList, // 新增, ,
                    update: updateUserList // 修改
                }

                // 提交表单
                const { code, message } = await textMap[this.dialogStatus](params)

                // 失败
                // if (code != 200) { this.$message.error(message); return };
                // 成功
                this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                        this.visible = false
                        this.$emit('getList')
                    }
                })
            })
        }

    }
}
</script>

<style lang="scss">
.mod-menu {
    .menu-list__input,
    .icon-list__input {
        > .el-input__inner {
            cursor: pointer;
        }
    }
    &__icon-popover {
        width: 458px;
        overflow: hidden;
    }
    &__icon-inner {
        width: 478px;
        max-height: 258px;
        overflow-x: hidden;
        overflow-y: auto;
    }
    &__icon-list {
        width: 458px;
        padding: 0;
        margin: -8px 0 0 -8px;
        > .el-button {
            padding: 8px;
            margin: 8px 0 0 8px;
            > span {
                display: inline-block;
                vertical-align: middle;
                width: 18px;
                height: 18px;
                font-size: 18px;
            }
        }
    }
    .icon-list__tips {
        font-size: 18px;
        text-align: center;
        color: #e6a23c;
        cursor: pointer;
    }
}
</style>
